import { ajax } from "./util.js"
let ul = document.querySelector(".list ul")

ajax.post("/list", {}, function(data){
  let str = ""
  data.forEach(item => {
    str += `<li>
      <h3>${item.title}</h3>
      <div class="content">
        <p>${item.content}</p>
        <div>
        
          <span>${item.username}</span>
          <a href="/edit?id=${item._id}">编辑</a>
          <a href="#" id="del">删除</a>
        </div>
      </div>
    </li>`
  })
  ul.innerHTML = str
})
ul.onclick=(e)=>{
    if(e.target.id == "del") {
        //阻止默认跳转行为
        e.preventDefault()
        function getQueryString(name) {
          const url_string = e.target.previousElementSibling.href
          const url = new URL(url_string);
          return url.searchParams.get(name);
        }
        let id = getQueryString("id")
        console.log(id)
        if(confirm("确认删除吗")){
          ajax.get("/delete", {id}, (data) => {
            console.log(data)
          })
          window.location.href = "/"
        }
      }
}